
import axios from 'axios';
import Cookie from 'js-cookie';
import { getToken } from '@/utils';
import { Message } from 'element-ui';
import { getUserId } from "@/utils";
import router from '@/router'
// import { history, config } from 'ice';
// 拦截器 错误处理
// 拦截器 错误处理

const request = axios.create({
  baseURL: window.SITE_CONFIG['apiURL'],
  // baseURL: process.env.VUE_APP_BASE_API,
  // 可选的，全局设置 request 是否返回 response 对象，默认为 false
  // withCredentials: true,
});
// request.defaults.timeout = 3000;

request.interceptors.request.use(
  (config) => {
    // if (config.method === 'get' && config.url.indexOf('/data/query/queryMetadataData') > -1) {
    //   config.data = true;
    //   config.headers = {
    //     'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    //   };
    // }
    // 非用户模块请求头携带token
    if (
      config.url.indexOf('/login') < 0 &&
      config.url.indexOf('/get_enum_type') < 0
    ) {
      
      const token = getToken();
      if (token) {
        config.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带自定义token 请根据实际情况自行修改
        // config.headers['accessAccess-Token'] = token
        // 添加user_id后缀
      const id = getUserId()
      const hasParams = config.url.indexOf('?') < 0
      let url = config.url
      if(hasParams) {
        config.url = `${url}?user_id=${id}`
      } else {
        config.url = `${url}&user_id=${id}`
      }
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

request.interceptors.response.use(
  (response) => {
    // 请求成功：可以做全局的 toast 展示，或者对 response 做一些格式化
    // 普通请求
    const code = response.data.status
    if (code === 1) {
      return response.data;
    }
    if (code === -1) {
      Cookie.remove('MES_ADMIN_KEY');
      router.push('/login')
      return true;
    }
    Message({
      message: response.data.msg || '操作失败',
      type: 'error',
      duration: 3 * 1000,
      offset: 200
    });
    return Promise.reject(response);
  },
  async (err) => {
    const data = await Promise.resolve({ err });

    const status = data?.err?.response?.status;
    switch (status) {
      case 400:
        err.message = '错误请求';
        break;
      case 401:
        err.message = '未授权，请重新登录';
        history.push('/user/login');
        break;
      default:
        err.message = '连接错误';
        err.msgType = undefined;
    }
    Message.error(err.message);
    if (err.msgType === undefined) return err;
    return Promise.reject(err);
  },
);
export default request;
